<template>
    <div>
        <div class="toolbar">
            <el-form :inline="true" :model="q" size="mini">
                <el-form-item>
                    <el-button type="text" disabled>{{this.Timetype?'创建时间':'到账时间'}}
                    </el-button>
                    (
                    <el-button type="text" @click="toggleTimetype">点击切换</el-button>
                    )
                    <el-date-picker v-if="Timetype" v-model="q.created_at_begin" value-format="yyyy-MM-dd HH:mm:ss"
                                    type="datetime" placeholder="选择日期时间"></el-date-picker>
                    <el-date-picker v-else v-model="q.success_at_begin" value-format="yyyy-MM-dd HH:mm:ss"
                                    type="datetime" placeholder="选择日期时间"></el-date-picker>
                    -
                    <el-date-picker v-if="Timetype" v-model="q.created_at_end" value-format="yyyy-MM-dd HH:mm:ss"
                                    type="datetime" placeholder="选择日期时间"></el-date-picker>
                    <el-date-picker v-else v-model="q.success_at_end" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                                    placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="商户订单ID:">
                    <el-input v-model="q.mch_recharge_id" placeholder="商户订单ID" prefix-icon="el-icon-edit"></el-input>
                </el-form-item>
                <el-form-item label="所属商户：">
                    <el-select v-model="q.mch_id" clearable placeholder="请选择">
                        <el-option v-for="item in MerchantsList" :key="item.id" :label="item.name"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="订单类型:">
                    <el-select v-model="q.source" clearable placeholder="请选择">
                        <el-option v-for="item in orderType" :key="item.id" :label="item.text"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="收款账号ID:">
                    <el-input v-model="q.receipt_address_id" placeholder="收款账号ID" prefix-icon="el-icon-edit"></el-input>
                </el-form-item>
                <el-form-item v-if="this.$store.state.user.userinfo.agency_type == 2" label="代理账号:">
                  <select-agent v-model="q.agency_id"></select-agent>
                </el-form-item>
                <el-form-item label="用户ID:">
                    <el-input v-model="q.user_id" placeholder="用户ID" prefix-icon="el-icon-edit"></el-input>
                </el-form-item>
                <el-form-item label="支付方式:">
                    <el-select v-model="q.pay_type" clearable placeholder="请选择">
                        <el-option v-for="(item,index) in payMethod" :key="item" :label="item"
                                   :value="index"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="订单状态:">
                    <el-select v-model="q.status" clearable placeholder="请选择">
                        <el-option v-for="(item,index) in orderStatus" :key="item" :label="item"
                                   :value="index" v-if="index!=10"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="query">查询</el-button>
                    <el-button type="danger" @click="reload">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-row type="flex" class="row-bg btn-row" justify="end">
            <el-button size="mini" v-if="this.$store.getters.userinfo.agency_type === 1" @click="add" type="primary"
                       icon="el-icon-plus">新增订单
            </el-button>
        </el-row>
        <el-table :data="listData.items" v-loading.body="listLoading" @sort-change="sortlist" size="mini" stripe border
                  fit highlight-current-row>
            <el-table-column prop="id" label='订单ID' width="100"></el-table-column>
            <el-table-column prop="mch_recharge_id" label='商户订单ID' width="200"></el-table-column>
            <el-table-column prop="mch_name" label='所属商户' width="180"></el-table-column>
            <el-table-column prop="user_id" label='用户ID' width="80"></el-table-column>
            <el-table-column v-if="this.$store.state.user.userinfo.agency_type == 2" prop="agency_name" label='代理账号'
                             width="150"></el-table-column>
            <el-table-column prop="source" label='订单类型' width="100" :formatter="FormartToText"></el-table-column>
            <el-table-column label='支付方式' width="100">
                <template slot-scope="scope">{{$store.state.app.payType[scope.row.pay_type]}}</template>
            </el-table-column>
            <el-table-column prop="receipt_address_id" label='收款账号ID' width="130"></el-table-column>
            <el-table-column prop="amount" label='订单金额' width="100"></el-table-column>
            <el-table-column prop="real_amount" label='充值金额' width="100"></el-table-column>
            <el-table-column prop="recharge_amount" label='到账金额' width="100"></el-table-column>
            <el-table-column prop="chased_amount" label='追分金额' width="100"></el-table-column>
            <el-table-column prop="status" label='订单状态' width="130" :formatter="FormartToText"></el-table-column>
            <el-table-column prop="remark" label='备注' width="200" :show-overflow-tooltip="true"></el-table-column>

            <el-table-column prop="created_at" label='创建时间' width="200"></el-table-column>
            <el-table-column prop="success_at" label='到账时间' width="200"></el-table-column>
            <el-table-column prop="updated_at" label='最后更新时间' width="200"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
                <template slot-scope="scope">
                    <div>
                        <el-button type="primary" size="mini"
                                   v-if="scope.row.status===1 && $store.getters.userinfo.agency_type == 1"
                                   @click="transfer(scope.row)">上分
                        </el-button>
                        <el-button type="primary" size="mini"
                                   v-if="scope.row.status===3 && $store.getters.userinfo.agency_type == 2"
                                   @click="AddScore(scope.row)">追分
                        </el-button>
                        <el-button type="success" size="mini"
                                   v-if="scope.row.status===1 && $store.getters.userinfo.agency_type == 1"
                                   @click="CancelOrder(scope.row)">取消
                        </el-button>
                        <el-button v-if="scope.row.status === 8 && $store.getters.userinfo.agency_type == 2 "
                                   type="success" size="mini" @click="agreeOrder(scope.row)">通过
                        </el-button>
                        <el-button v-if="scope.row.status === 8 && $store.getters.userinfo.agency_type == 2"
                                   type="warning" size="mini" @click="refuseOrder(scope.row)">拒绝
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="q.page_no" :page-sizes="$store.state.app.pageSizeArr"
                           :page-size="q.page_size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="listData.total">
            </el-pagination>
        </div>
        <save-update v-if="showUpdate" :showUpdate.sync="showUpdate" :id="show_id" :AgencyType="AgencyType"
                     :MerchantsList="MerchantsList"></save-update>
        <transfre v-if="showTransfre" :showTransfre.sync="showTransfre" :id="show_id" :AgencyType="AgencyType"
                  :MerchantsList="MerchantsList">
        </transfre>
        <show-details v-if="showDetails" :showDetails.sync="showDetails" :id="show_id" :AgencyType="AgencyType"
                      :MerchantsList="MerchantsList">
        </show-details>
        <add-score v-if="showAddScore" :showAddScore.sync="showAddScore" :id="show_id"
                   :rowInfo="rowInfo"></add-score>
        <cancel-remark v-if="showCancel" :showCancel.sync="showCancel" :id="show_id"
                       :MerchantsList="showCancel"></cancel-remark>
    </div>
</template>

<script>
    import {getOrderList1, cancelOrder, sendRecharge, getAgencyInfo, agreeOrder, refuseOrder} from '@/api/index'
    import {FormartPayType, useVcode} from "../../utils/CommonJs"
    import transfre from './transfre.vue'
    import saveUpdate from './saveUpdate'
    import SelectAgent from '@/components/SelectAgent/index.vue'
    import showDetails from './details'
    import AddScore from './AddScore'
    import CancelRemark from './CancelRemark'

    import {queryFilter} from '@/utils/patch'

    export default {
        components: {showDetails, transfre, saveUpdate, AddScore, CancelRemark,SelectAgent},
        data() {
            return {
                listData: {},
                q: {page_size: 30, page_no: 1},
                listLoading: false,
                showUpdate: false,
                showTransfre: false,
                showDetails: false,
                showCancel: false,
                settleCycle: this.$store.state.app.settleCycle,
                show_id: null,
                AgencyType: this.$store.state.app.AgencyType,
                MerchantsList: [],
                Timetype: true,
                showAddScore: false,
                orderStatus: this.$store.state.app.orderStatus,
                orderType: [
                    {id: 1, text: '手动充值'},
                    {id: 2, text: '自动充值'}
                ],
                payMethod: this.$store.state.app.payType,
                rowInfo: {}
            }
        },
        activated() {
            this.getAgencyInfo()
            this.getList()
        },
        deactivated() {
            this.listLoading = false
        },
        methods: {
            add() {
                this.show_id = null
                this.showUpdate = true
            },
            update(row) {
                this.show_id = row.id
                this.showUpdate = true
            },
            transfer(row) {
                this.$prompt(`确定通过用户【${row.user_id}】充值【${row.real_amount}】的申请？请输入备注：`, '上分申请', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then((promptobj) => {
                    if (!promptobj.value) {
                        promptobj.value = ''
                    }
                    useVcode(this, () => {
                        sendRecharge(row.id, {'remark': promptobj.value}).then(res => {
                            if (res.status === 0) {
                                let msg = '上分成功！'
                                this.$message({type: 'success', message: msg, duration: 3000, showClose: true})
                                this.getList()
                            }
                        })
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    })
                })
            },

            Details(row) {
                this.show_id = row.id
                this.showDetails = true
            },
            query() {
                this.q = Object.assign(this.q, {page_no: 1, page_size: 30})
                this.getList()
            },
            reload() {
                this.q = {page_size: 30, page_no: 1, agency_type: 1}
                this.getList()
            },
            sortlist(sort) {
                this.q.$orderby = sort.prop
                this.getList()
            },
            handleSizeChange(val) {
                this.q.page_size = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.q.page_no = val
                this.getList()
            },
            getList() {

                this.q = queryFilter(this.q)
                getOrderList1(this.q).then(res => {
                    if (res.status === 0) {
                        this.listLoading = false
                        this.listData = res.data
                        this.listData.items = Array.from(res.data.items, x => Object.assign({}, x, {
                            amount: Number(x.amount) / 100,
                            real_amount: Number(x.real_amount) / 100,
                            recharge_amount: Number(x.recharge_amount) / 100,
                            chased_amount: Number(x.chased_amount) / 100,

                        }))
                        console.log(this.listData)
                    }
                })
            },
            toggleTimetype() {
                if (this.Timetype) {
                    delete this.q.created_at_begin
                    delete this.q.created_at_end
                    this.Timetype = !this.Timetype
                } else {
                    delete this.q.success_at_begin
                    delete this.q.success_at_end
                    this.Timetype = !this.Timetype
                }
            },
            AddScore(row) {
                this.show_id = row.id
                this.showAddScore = true
                this.rowInfo = row
            },
            CancelOrder(row) {
                this.$prompt(`确定取消用户【${row.user_id}】充值【${row.real_amount}】的订单？请输入备注：`, '取消申请', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then((promptobj) => {
                    if (!promptobj.value) {
                        promptobj.value = ''
                    }
                    cancelOrder(row.id, {'remark': promptobj.value}).then(res => {
                        if (res.status === 0) {
                            let msg = '取消订单成功！'
                            this.$message({type: 'success', message: msg, duration: 3000, showClose: true})
                            this.getList()
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    })
                })
            },
            getAgencyInfo() {
                getAgencyInfo().then(res => {
                    if (res.status === 0) {
                        this.MerchantsList = res.data.mchs
                    }
                })
            },
            FormartToText(row, column) {
                switch (column.property) {
                    case 'pay_method':
                        return this.$store.state.app.PayMethodType(row.pay_method)
                    case 'pay_type':
                        return FormartPayType(row.pay_type)
                    case 'source':
                        return this.$store.state.app.orderType[row.source]
                    case 'status':
                        return this.$store.state.app.orderStatus[row.status]
                }
            },
            agreeOrder(row) {
                this.$confirm(`确认通过 ${row.id} 的上分申请吗？`, '订单审核', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    useVcode(this, () => {
                      agreeOrder(row.id).then(res => {
                        if (res.status === 0) {
                          let msg = '同意' + row.id + ' 的上分申请成功！'
                          this.$message({type: 'success', message: msg, duration: 5000})
                          this.getList()
                        }
                      })
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    })
                })
            },
            refuseOrder(row) {
                this.$confirm(`确认拒绝 ${row.id} 的上分申请吗？`, '订单审核', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                  useVcode(this, () => {
                    refuseOrder(row.id).then(res => {
                      if (res.status === 0) {
                        let msg = '拒绝' + row.id + ' 的上分申请成功！'
                        this.$message({type: 'success', message: msg, duration: 5000})
                        this.getList()
                      }
                    })
                  })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    })
                })
            }


        },
        watch: {
            showUpdate() {
                if (!this.showUpdate) {
                    this.getList()
                }
            },
            showCancel() {
                if (!this.showCancel) {
                    this.getList()
                }
            },
            showAddScore() {
                if (!this.showAddScore) {
                    this.getList()
                }
            }
        }
    }
</script>
